/**
 * 树形UI控件，支持拖拽;CheckBox;异步加载;节点上、下、左、右移动;右键菜单
 * @author zhaojh
 */
function TreeObj(o){
	this.editor = o;
	this.baseObj = null;
	this.tree = null;
	this.contextMenu = null;
	this.basePath = null;
	
}

TreeObj.prototype.toString = function(){
	return "TreeObj";
}

//TreeObj.prototype.getBaseObj = function(){
//	if(this.baseObj == null){
//		this.baseObj = new BaseObj(this.editor);
//	}
//	return this.baseObj;
//}

TreeObj.prototype.onReady = function(){
	var $editor = jQuery(this.editor);
	
	//加载树容器DIV的默认样式
	if(!$editor.attr("style") || jQuery.trim($editor.attr("style")) == ""){
		$editor.css({
           'background-color':'#f5f5f5',
         /*'border' :'1px solid Silver', */
           'overflow':'auto'
		});
	}
	
	//树的宽度
	if(!$editor.attr("width") || jQuery.trim($editor.attr("width")) == ""){
		$editor.css("width","350px");
	}else{
		$editor.css("width",$editor.attr("width"));
	}
	
	//树的高度
	if(!$editor.attr("height") || jQuery.trim($editor.attr("height")) == ""){
		$editor.css("height","518px");
	}else{
		$editor.css("height",$editor.attr("height"));
	}
	
	//开始构建树型构件
	var treeId = $editor.attr("id");		
	this.tree = new dhtmlXTreeObject(treeId,"100%","100%",0);
	
	//树的主题样式
	this.tree.setSkin("dhx_skyblue");
	var treeSkin = $editor.attr("treeSkin");
	if(!treeSkin || jQuery.trim(treeSkin) == ""){
		treeSkin = "skyblue";
	}
	
	//树所用图片路径
	var treeImagePath = $editor.attr("treeImagePath");
	if(!treeImagePath || jQuery.trim(treeImagePath) == ""){
		this.tree.setImagePath("easytogo/ui/tree/dhtmlxtree/image/" + treeSkin + "/");
	}else{
		this.tree.setImagePath(treeImagePath);
	}
	
	//树是否支持拖拽
	var isEnableDrag = $editor.attr("isEnableDrag");
	if(jQuery.trim(isEnableDrag) == "true"){
		this.tree.enableDragAndDrop(true);
	}
	
	//是否显示CheckBox
	var isEnableCheckBoxes = $editor.attr("isEnableCheckBoxes");
	if(jQuery.trim(isEnableCheckBoxes) == "true"){
        this.tree.enableCheckBoxes(true);
        
        //选中父节点是否影响子节点选中，true影响
        var isEnableThreeStateCheckboxes = $editor.attr("isEnableThreeStateCheckboxes");
        if(jQuery.trim(isEnableThreeStateCheckboxes) == "true"){
        	this.tree.enableThreeStateCheckboxes(true);
        }
    }
	
	//是否显示radio
	var isEnableRadio = $editor.attr("isEnableRadio");
	if(jQuery.trim(isEnableRadio) == "true"){
		this.tree.enableRadioButtons(true);
	}
	
	//树是否支持右键菜单
	var isShowContextMenu = $editor.attr("isShowContextMenu");
	if(jQuery.trim(isShowContextMenu) == "true"){
		//开始构建树的右键菜单
//		this.contextMenu = new dhtmlXMenuObject();
		this.contextMenu = new ContextMenu();
		
		//指定右键菜单图片路径
		var menuImagePath = $editor.attr("menuImagePath");
		if(!menuImagePath || jQuery.trim(menuImagePath) == ""){
			this.contextMenu.setIconsPath("easytogo/ui/tree/dhtmlxtree/image/contextMenu/");
		}else{
			this.contextMenu.setIconsPath(menuImagePath);
		}
		
		//菜单加载数据
		var $url = jQuery.trim($editor.attr("menuLoadUrl"));
		if(!$url){
		   alert("缺少右键菜单数据来源，请设置标签的[menuLoadUrl]属性！")
		   return;
		}
		this.contextMenu.renderAsContextMenu();
		this.contextMenu.loadXML(jQuery.trim($editor.attr("menuLoadUrl")));
		
		//将右键菜单和树绑定
		this.tree.enableContextMenu(this.contextMenu.getMenu());
		//记录右键菜单依附在哪棵树上,目的是为了提供默认右键菜单添加、删除、上移、下移、左移、右移节点功能
		this.contextMenu.setTree(this);
		
		this.contextMenu.setDefaultItemClickHandler();
	}
	
	//树节点默认加载数据路径
	var treeAutoLoadUrl = $editor.attr("treeAutoLoadUrl");
	if(treeAutoLoadUrl && jQuery.trim(treeAutoLoadUrl) != "" ){
		this.tree.setXMLAutoLoading(treeAutoLoadUrl);
	}
	
//	//为了支持大数据量加载,异步、不展开加载2M以上数据使用
//	this.tree.enableSmartRendering(true);
	
	//加载数据
	var treeLoadUrl = jQuery.trim($editor.attr("treeLoadUrl"));
	var treeDataMode = $editor.attr("treeDataMode");
	if(treeDataMode && jQuery.trim(treeDataMode) == "xml"){
		this.tree.loadXML(treeLoadUrl);//xml 格式数据加载方式
	}else{
        //JSON格式数据为默认加载格式
        this.tree.setDataMode("json");//设置数据加载方式为JSON
        if(isJSONString(treeLoadUrl)){
        	var treeJson = parseJSON(treeLoadUrl);
        	
            //直接加载JSON对象,但不加载空JSON对象
        	if(!isEmptyObject(treeJson)){
        		//判断返回子树的父节点是否存在,不存在，则将子树的父节点改为“0”
                if(treeJson.id != "0"){
                    treeJson.id = "0";
                }
        		this.tree.loadJSONObject(treeJson);
        	}
        }else{
            //响应url请求
            this.tree.loadJSON(treeLoadUrl); 
        }
        
	}

}

/**
 * 重新加载树
 */
TreeObj.prototype.reload = function(){
	var $editor = jQuery(this.editor);
    var nodeIds = this.getSubNodesIds("0").split(',');

    if (nodeIds == "") {
        return;
    }

    for (var i = 0; i < nodeIds.length; i++) {
        this.deleteNode(nodeIds[i]);
    }

    //加载数据
    var treeLoadUrl = jQuery.trim($editor.attr("treeLoadUrl"));
    var treeDataMode = $editor.attr("treeDataMode");
    if(treeDataMode && jQuery.trim(treeDataMode) == "xml"){
        this.tree.loadXML(treeLoadUrl);//xml 格式数据加载方式
    }else{
        //JSON格式数据为默认加载格式
        this.tree.setDataMode("json");//设置数据加载方式为JSON
        if(isJSONString(treeLoadUrl)){
            var treeJson = parseJSON(treeLoadUrl);

            //直接加载JSON对象,但不加载空JSON对象
            if(!isEmptyObject(treeJson)){
                //判断返回子树的父节点是否存在,不存在，则将子树的父节点改为“0”
                if(treeJson.id != "0"){
                    treeJson.id = "0";
                }
                this.tree.loadJSONObject(treeJson);
            }
        }else{
            //响应url请求
            this.tree.loadJSON(treeLoadUrl);
        }

    }
}

/**
 * 根据节点ID判断节点是否存在
 * @param {} id 节点ID
 * @return true: 节点存在， false:节点不存在
 */
TreeObj.prototype.isExistByNodeId = function(id){
	if(this.tree.ak(id)){
		return true;
	}else{
		return false;
	}
}

/**
 * 返回原生的被封装的js树形组件
 * @return {}
 */
TreeObj.prototype.getTree = function(){
	return this.tree;
}

/**
 * 返回原生的被封装的右键菜单组件
 * @return {}
 */
TreeObj.prototype.getContextMenu = function(){
	return this.contextMenu;
}

/**
 * 绑定节点双击事件
 * @param {} func
 */
TreeObj.prototype.setOnDblClickHandler = function(func){
	if(typeof func == "function"){
		this.tree.setOnDblClickHandler(func);
	}
}

/**
 * 设置节点点击事件
 * @param {} func
 */
TreeObj.prototype.setOnClickHandler = function(func){
	if(typeof func == "function"){
        this.tree.setOnClickHandler(func);
    }
}

/**
 * 设置节点拖拽事件,此事件中节点关系无变化发生
 */
TreeObj.prototype.setDragHandler = function(func){
    if(typeof func == "function"){
        this.tree.setDragHandler(func);
    }   
}

//TreeObj.prototype.setDragInHandler = function(func){
//    if(typeof func == "function"){
//        this.tree.setDragInHandler(func);
//    }   	
//}

/**
 * 设置节点拖拽事件,此事件中节点关系已发生变化
 * @param {} func
 */
TreeObj.prototype.setDropHandler = function(func){
    if(typeof func == "function"){
        this.tree.setDropHandler(func);
    }   	
}

/**
 * 带CheckBox的，在改变CheckBox状态时出发的属性
 * @param {} func
 */
TreeObj.prototype.setOnCheckHandler = function(func){
    if(typeof func == "function"){
        this.tree.setOnCheckHandler(func);
    } 	
}

/**
 * 通过节点ID取得此节点存储的以key为名的附加数据
 * @param {} id 节点ID
 * @param {} key
 * @return {}
 */
TreeObj.prototype.getUserData = function(id, key){
	if(!id) null;
	return this.tree.getUserData(id, key);
}

/**
 * 给指定节点设置 user data
 * @type 私有方法
 * @param {} itemId
 * @param {} name
 * @param {} value
 */
TreeObj.prototype._setUserData = function(itemId, name, value){
	this.tree.setUserData(itemId, name, value);
}



/**
 * 获取节点ID为给定值的节点Text
 * @param {} id
 * @return {}
 */
TreeObj.prototype.getNodeText = function(id){
	if(!id) return;
	return this.tree.getItemText(id);
}

/**
 * 获得选中节点的ID
 * @return {}
 */
TreeObj.prototype.getSelectedNodeId = function(){
	return this.tree.getSelectedItemId();
}

/**
 * 获得选中节点的Text
 * @return {}
 */
TreeObj.prototype.getSelectedNodeText = function(){
    return this.tree.xB();
}

/**
 * 添加节点
 * @param {} parentId
 * @param {} itemId
 * @param {} itemText
 */
TreeObj.prototype.addNode = function(parentId, itemId, itemText){
	this.tree.insertNewChild(parentId, itemId, itemText, 0, 0, 0, 0, "SELECT");
}

/**
 * 通过JSON给某一节点添加子节点（或子树）
 * @param {} json 为cn.com.victorysoft.eaf.util.TreeUtil.getTreeJSON 方法返回的json字符串
 */
TreeObj.prototype.addNodeByJSON = function(json){
    if(typeof json == "string"){
       var o = parseJSON(json);
       var items = o.item;
       if(items && isArray(items)){
            this.__addNode(o.id, items);
       }
    }
}

/**
 * @type private
 * @param {} pid
 * @param {} o
 */
TreeObj.prototype.__addNode = function(pid, o){
    if(isArray(o)){
        for(var i=0; i<o.length; i++){
            this.addNode(pid,o[i].id,o[i].text);
           
            var uds = o[i].userdata;
            if(uds && isArray(uds)){
                 for(var j=0; j<uds.length; j++){
                     this._setUserData(o[i].id,uds[j].name,uds[j].content);
                 }
            }
            
            var item = o[i].item;
            if(item && isArray(item)){
                this.__addNode(o[i].id, item);
            }
        }
    }	
}

/**
 * 设置节点的显示图片
 * @param {} itemId
 * @param {} kQ
 * @param {} kS
 * @param {} nI
 */
TreeObj.prototype.setNodeImage2 = function(itemId, kQ, kS, nI){
	this.tree.setItemImage2(itemId, kQ, kS, nI);
}

/**
 * 获取给定ID节点所在树中的层级
 * @param {} id
 * @return {}
 */
TreeObj.prototype.getLevel = function(id){
	if(!id) return;
	return this.tree.getLevel(id);
}

/**
 * 删除节点
 * @param {} node
 */
TreeObj.prototype.deleteNode = function(id){
	if(!id) return;
	this.tree.deleteItem(id,true);
}

/**
 * 节点上移，只能在兄弟节点间移动
 * @param {} id
 */
TreeObj.prototype.moveUp = function(id){
	if(!id) return;
	this.tree.moveItem(id,"up_strict");
	this.selectNode(id);
}

/**
 * 节点下移，只能在兄弟节点间移动
 * @param {} id
 */
TreeObj.prototype.moveDown = function(id){
	if(!id) return;
    this.tree.moveItem(id,"down_strict");
    this.selectNode(id);
}

/**
 * 节点左移，将节点提升为父节点的最后一个兄弟
 * @param {} id
 */
TreeObj.prototype.moveLeft = function(id){
	if(!id) return;
	var pid = this.getParentId(id);
	var ppid = this.getParentId(pid);
    var subids = this.tree.getSubItems(ppid); //get parent node's  all subnode id

    if(subids.length > 1 && subids.indexOf(",") != -1){
    	subid = subids.split(",");
    }else{
    	subid = new Array();
    	subid.push(subids);
    }

    //move selected node
    if(subid.length>1 ){
    	this.tree.moveItem(id,"item_sibling_next",subid[subid.length-1]);
        this.selectNode(id);
    }
    
}

/**
 * 节点右移，将节点降级为它直接前一个兄弟节点的最后一个子节点。
 * @param {} id
 */
TreeObj.prototype.moveRight = function(id){
	if(!id) return;
	var pid = this.getParentId(id);
	var subids = this.tree.getSubItems(pid); //get parent node's  all subnode id

	var subid = subids.split(",");
	var preid;
	//get current node's prerior node id
	for(var i=0; i<subid.length; i++){
		preid = subid[i-1];
		if(subid[i] == id) break;
	}

	// move selected node
	if(preid && preid != id){
		this.tree.moveItem(id,"item_child",preid);
        this.selectNode(id);
	}
    
}

/**
 * 选中给定ID的节点，将节点标识为选中状态
 * @param {} id
 */
TreeObj.prototype.selectNode = function(id){
	if(!id) return;
    this.tree.selectItem(id);
}

/**
 * 获得给定ID节点的父节点ID
 * @param {} id
 * @return {}
 */
TreeObj.prototype.getParentId = function(id){
	if(!id) return;
	return this.tree.getParentId(id);
}

/**
 * 取得给定ID的节点的所有子节点ID,返回的是一个ID字符创，以","为分隔符。
 * @param {} id
 * @return {}
 */
TreeObj.prototype.getSubNodesIds = function(id){
	if(!id) return;
	return this.tree.getSubItems(id);
}

/**
 * 设置给定ID节点的Text内容
 * @param {} id
 * @param {} text
 */
TreeObj.prototype.setNodeText = function(id, text){
	if(!id) return;
	this.tree.setItemText(id,text);
}

/**
 * 在带CheckBox时，返回CheckBox选中的节点ID
 * @return {}
 */
TreeObj.prototype.getAllChecked = function(){
	return this.tree.getAllChecked();
}

/**
 * 在带CheckBox时，控制指定节点的CheckBox状态
 * @param {} id
 * @param {} bV true:选中，false:未选中
 */
TreeObj.prototype.setCheck = function(id, bV){
	this.tree.setCheck(id, bV);
}

TreeObj.prototype.getContextID = function(){
	return this.tree.contextID;
}

/**
 * 展开整克数的全部节点
 */
TreeObj.prototype.expandAll = function(){
	this.tree.openAllItems(0);
}

/**
 * 展开指定节点的所有子节点（包括子孙）
 * @param {} id
 */
TreeObj.prototype.expand = function(id){
	this.tree.openAllItems(id);
}

/**
 * 只展开某个节点的一层子节点（不包括子孙）
 * @param {} id
 */
TreeObj.prototype.openItem = function(id){
    this.tree.openItem(id);
}

/**
 * 关闭整棵树的所有节点
 * @param {} id
 */
TreeObj.prototype.collapseAll = function(){
    this.tree.closeAllItems(0);
}

/**
 * 关闭树中给定节点的所有子节点（包括子孙）
 * @param {} id
 */
TreeObj.prototype.collapse = function(id){
    this.tree.closeAllItems(id);
}

/**
 * 关闭给定节点的子节点（不包括子孙）
 * @param {} id
 */
TreeObj.prototype.closeItem = function(id){
    this.tree.closeAllItems(id);
}

TreeObj.prototype.openSingleItem = function(id){
	if(!id) return;
	var pid = this.getParentId(id);
	var bortherId = this.getSubNodesIds(pid.toString());
	if(bortherId && bortherId.trim()!=""){
		if(bortherId.indexOf(",")>-1){
			var ids = bortherId.split(",");
			for(var i=0; i<ids.length; i++){
				this.collapse(ids[i]);
			}
		}else{
			this.collapse(bortherId);
		}
	}
	this.openItem(id);
}


//======================= 树右键菜单 ========================//

/**
 * 树的右键菜单
 * @param {} o
 */
function ContextMenu(){
	this.menu = new dhtmlXMenuObject();
	this.tree = null;
}

/**
 * 设置右键菜单要加载的图片路径
 * @param {} imgPath
 */
ContextMenu.prototype.setIconsPath = function(imgPath){
	this.menu.setIconsPath(imgPath);
}

/**
 * 设置菜单为右键弹出模式
 */
ContextMenu.prototype.renderAsContextMenu = function(){
	this.menu.renderAsContextMenu();
}

/**
 * 加载菜单数据
 * @param {} url
 */
ContextMenu.prototype.loadXML = function(url){
	this.menu.loadXML(url);
}

/**
 * 获得ContextMenu类封装的原生js对象
 * @return {}
 */
ContextMenu.prototype.getMenu = function(){
	return this.menu;
}

/**
 * 设置右键菜单所依附的原生树
 * @param {} t
 */
ContextMenu.prototype.setTree = function(t){
	if(this.tree == null){
		this.tree = t;
	}
}

/**
 * 注册右键菜单，菜单项点击事件
 * @param {} func
 */
ContextMenu.prototype.setItemClickHandler = function(func){
	if(typeof func == "function"){
        this.menu.attachEvent("onClick",func);
    } 
}

ContextMenu.prototype.setDefaultItemClickHandler = function(){
	var that = this;
	this.setItemClickHandler(function(menuitemId){
		var id = that.tree.getContextID();
        //add node
        if(jQuery.trim(menuitemId)=="add"){
            that.addNode(id);
        }
        
        //delete node
        if(jQuery.trim(menuitemId)=="delete"){
            that.deleteNode(id);
        }
        
        //rename node's name
        if(jQuery.trim(menuitemId)=="rename"){
            that.nodeRename(id);
        }   
        
        //move up node
        if(jQuery.trim(menuitemId)=="up"){
            if(that.nodeMoveUp(id)){
            	that.tree.moveUp(id);
            }
        }
        
        //move down node
        if(jQuery.trim(menuitemId)=="down"){
            if(that.nodeMoveDown(id)){
            	that.tree.moveDown(id);
            }
        }
        
        //move left node
        if(jQuery.trim(menuitemId)=="left"){
            if(that.nodeMoveLeft(id)){
            	that.tree.moveLeft(id);
            }
        }
        
        //move right node
        if(jQuery.trim(menuitemId)=="right"){
            if(that.nodeMoveRight(id)){
            	that.tree.moveRight(id);
            }
        }	
	})
}

ContextMenu.prototype.addNode = function(id){}

ContextMenu.prototype.deleteNode = function(id){}

ContextMenu.prototype.nodeRename = function(id){}

ContextMenu.prototype.nodeMoveUp = function(id){return true;}

ContextMenu.prototype.nodeMoveDown = function(id){return true;}

ContextMenu.prototype.nodeMoveLeft = function(id){return true;}

ContextMenu.prototype.nodeMoveRight = function(id){return true;}

ContextMenu.prototype.addEventListener = function(eventid, handler){
	var func;
	if(typeof handler == "function"){
		func = handler;
	}else{
		return;
	}
	
	if(jQuery.trim(eventid) == "addNode"){
		this.addNode = func;
	}
	
	if(jQuery.trim(eventid) == "deleteNode"){
		this.deleteNode = func;
	}
	
	if(jQuery.trim(eventid) == "nodeRename"){
		this.nodeRename = func;
	}
	
	if(jQuery.trim(eventid) == "nodeMoveUp"){
		this.nodeMoveUp = func;
	}
	
	if(jQuery.trim(eventid) == "nodeMoveDown"){
		this.nodeMoveDown = func;
	}
	
	if(jQuery.trim(eventid) == "nodeMoveLeft"){
		this.nodeMoveLeft = func;
	}
	
	if(jQuery.trim(eventid) == "nodeMoveRight"){
		this.nodeMoveRight = func;
	}
}